<template>
    <div>
      <div class="systemInfo">
        <span class="gap"> [板卡状态]  AD数据心跳 : {{ allData.card_status.AD_data }} 包</span>
        <span> DDC数据心跳 : {{ allData.card_status.DDC_data }} 包</span>
        <span> 板卡类型 : {{ allData.card_status.card_type }}</span>
        <span> 采集卡温度 : {{ allData.collect_temperature }} ℃</span>    
        <span> GPS状态: {{ allData.GPS_status }}</span>
      </div>
      <div class="resourceInfo">
        <span class="gap"> [系统信息]  CPU使用率 : {{ allData.systemInfo.cpu_percent.toFixed(2) }} %</span>
        <span> GPU使用率 : {{ allData.systemInfo.gpu_percent.toFixed(2) }} %</span>
        <span> 内存使用率 : {{ allData.systemInfo.memory_percent.toFixed(2) }} %</span>
        <span> 虚拟内存使用率 : {{ allData.systemInfo.virtualMemory_percent.toFixed(2) }} %</span>
        <span> 硬盘剩余容量/总容量 : {{ allData.systemInfo.disk_free.toFixed(2) }} G/{{ allData.systemInfo.disk_total.toFixed(2) }} G</span>
      </div>
      <div class="channelSelect" :offset="0">
          <el-button type="info" @click="toGetCollectData(0)">通道1</el-button>
          <el-button type="info" @click="toGetCollectData(1)">通道2</el-button>
          <el-button type="info" @click="toGetCollectData(2)">通道3</el-button>
          <el-button type="info" @click="toGetCollectData(3)">通道4</el-button>
          <el-button type="danger" @click="stopAllPath">停止所有采集通路</el-button>
          <span class="time"> 
            <span class="storageRate"> 存储速率 : {{ StorageRate }} B/s </span>
            <span> {{ allData.time_type }} : {{ allData.time_value }} </span>
          </span>
      </div>
      <el-table
        max-height="85vh" style="width: 100% ; font-size: 14px " border
        @selection-change="handleSelectionChange"
        :data="tableData" 
        highlight-current-row
        ref="singleTableRef"
        :lazy="true"
      >
          <el-table-column :label= "'通道 ' + (current_chid + 1) " align="center">
            <el-table-column type="selection"  width="60rem" align="center"/>
            <el-table-column prop="pathid" label="DDC通道号" width="110rem" align="center"/>
            <el-table-column prop="collect_status" label="采集状态" width="120rem" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.collect_status == 1" effect="light" type="success">
                    正在采集
                  </el-tag>
                  <el-tag v-else-if="scope.row.collect_status == 0" effect="light" type="danger">
                    停止采集
                  </el-tag>
                  <el-tag v-else-if="scope.row.collect_status == 2" effect="light" type="warning">
                    等待采集
                  </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="freq" label="频点(Hz)" align="center"/>
            <el-table-column prop="gain" label="增益(dB)" align="center"/>
            <el-table-column prop="amplitude" label="幅度" align="center"/>
            <el-table-column prop="touch_time" label="触发时间" align="center"/>
            <el-table-column prop="frame_count" label="存储帧数" align="center"/>
            <el-table-column fixed="right" label="操作" width="220rem" align="center">
                <template #default="scope">
                    <el-button round type="danger" size="small" 
                    @click="stopOnePath(scope.row.pathid)" :disabled=" scope.row.collect_status == 1 ?false:true">拆链</el-button>
                    <el-button type="primary" size="small" round dark=true
                    @click="openDialog('修改采集参数',scope.row.pathid)" :disabled=" scope.row.collect_status == 1 ?false:true">修改</el-button>
                    <!-- <el-button round type="success" size="small" 
                    @click="startOnePath(scope.row.pathid)" :disabled=" scope.row.collect_status == 0 ?false:true">建链</el-button> -->
                </template>
            </el-table-column>
          </el-table-column>
      </el-table>
    
      <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            :width="dialog.width"
            append-to-body
            center
          >
              <el-form label-width="4rem">
      
                <el-form-item label="频点" prop="freq">
                  <el-input type="number"
                    v-model.number="currentDDC_data.freq"
                  />
                </el-form-item>
                <el-form-item label="增益" prop="gain">
                  <el-input type="number"
                    v-model.number="currentDDC_data.gain"
                  />
                </el-form-item>
    
              </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="confirmModify" >确认修改</el-button>
                <el-button @click="cancelModify">取消修改</el-button>
              </span>
            </template>
      </el-dialog>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted,onUnmounted, watch } from 'vue'
    import { ElTable,ElMessage } from 'element-plus'
    import { Download,Upload,Open,TurnOff } from '@element-plus/icons-vue'
    import { Row } from 'element-plus/es/components/table-v2/src/components';
    import CollectApi from '../apis/collectHttp.js'
    const current_chid = ref(0)
    const tableData = ref([
        {
            "pathid":0,
            "collect_status":0         
        },{
            "pathid":1,
            "collect_status":1           
        },{
            "pathid":3,
            "collect_status":2
        },{"pathid":4,
        },{"pathid":5,
        },{"pathid":6,
        },{"pathid":7,
        },{"pathid":8,
        },{"pathid":9,
        },{"pathid":10,
        },{"pathid":11,
        },{"pathid":12,
        },{"pathid":13,
        },{"pathid":14,
        },{"pathid":15,
        },{"pathid":16,
        },{"pathid":17,
        },{"pathid":18,
        },{"pathid":19,
        },{"pathid":20,
        },{"pathid":21,
        },{"pathid":22,
        },
    ])
    const allData = reactive({
      "ch0_data": [
          {
              "pathid": 0, //0-63 
              "freq": 0, //频点
              "gain": 0, //增益
              "amplitude": 0, //幅度
              "touch_time": " ", //触发时间
              "frame_count": 0, //存储帧数
              "collect_status":0
          }
      ],
      "ch1_data": [
          {
              "pathid": 0, //0-63
              
          }
      ],
      "ch2_data": [
          {
              "pathid": 0, //0-63
          }
      ],
      "ch3_data": [
          {
              "pathid": 0, //0-63
          }
      ],
      "card_status": { //采集卡的一些状态信息，和采集c/s界面完全一样
          "AD_data": 0, //AD数据心跳 int
          "DDC_data": 122, //DDC数据心跳 int
          "card_type": "四通道485T", //板卡类型
      },
      "collect_temperature": 0, //采集卡温度 摄氏度℃
      "time_type": " ", //时间类型：北斗还是别的什么
      "time_value": " ", //时间值是多少,string 
      "GPS_status": "未知", //GPS状态 string
      "systemInfo":{
        "cpu_percent":0,//CPU使用率，%百分比
        "memory_percent":0,//内存使用率，%百分比
        "virtualMemory_percent": 0,//虚拟内存使用率，%百分比数值
        "gpu_percent":0,//GPU使用率，%百分比
        "disk_free":0,	//硬盘剩余容量，单位G
        "disk_total":0//硬盘总容量，单位G
      }
    })
    const CurCollectPath = ref(0)//当前采集路数
    const storageFrames = ref(0)//存储帧数
    const StorageRate = ref(0)//采集速率
    //处理选择的行改变
    const multiSelection = ref([])//用于加载所有要开始/停止的ID集合
    const handleSelectionChange = async (selection:any) => {
        multiSelection.value = selection.map((item:any) => item.pathid)
    }
    const toGetCollectData = async (Channel:number) => {
        current_chid.value = Channel;    
    //调用同一个接口发送不同的通道(0~3)请求不同的数据,赋值给tableData
        switch(Channel){
          case 0: tableData.value = allData["ch0_data"] 
            break
          case 1: tableData.value = allData["ch1_data"] 
            break
          case 2: tableData.value = allData["ch2_data"] 
            break
          case 3: tableData.value = allData["ch3_data"] 
            break
        }
    }
    
  const ws = ref() //socket
  let rec
  let isConnect = false
  let checkMsg = "heartbeat"
  const CreateWebSocket = () => {
    try {
      initWebsocket()
    }catch (e){
      console.log("尝试连接失败");
      // reConnect()
    }
  }
  const initWebsocket = () => {
    const svrHost = window.location.hostname
    // let url = 'ws://192.168.1.22:7888' 
    // if(svrHost.length < 1)
    //   url = "ws://192.168.1.22:7888"

    if("WebSocket" in window)
      ws.value = new WebSocket(`ws://${window.location.host}/collectWS`);
    
    ws.value.onopen = () => {
      console.log('[采集ws.onopen]:enter')     
    }

    ws.value.onmessage =  (e) => {
      let socketData = JSON.parse(e.data)
      //判断有无错误信息
      if("error" in socketData ){//Json中包含error
        if(Array.isArray(socketData["error"]) && socketData["error"].length > 0){//是数组并且长度大于0
          ElMessage.error("采集CS软件存在错误，")
        }
      }
      CurCollectPath.value = 0
      socketData.ch0_data.forEach((item) => {
        if(item.collect_status == 1){
          CurCollectPath.value ++
          storageFrames.value = item.frame_count
        }
      })
      socketData.ch1_data.forEach((item) => {
        if(item.collect_status == 1){
          CurCollectPath.value ++
        }
      })
      socketData.ch2_data.forEach((item) => {
        if(item.collect_status == 1){
          CurCollectPath.value ++
        }
      })
      socketData.ch3_data.forEach((item) => {
        if(item.collect_status == 1){
          CurCollectPath.value ++
        }
      })

      allData.GPS_status = socketData.GPS_status
      allData.card_status.AD_data = socketData.card_status.AD_data
      allData.card_status.DDC_data = socketData.card_status.DDC_data
      allData.card_status.card_type = socketData.card_status.card_type
      allData.ch0_data = socketData.ch0_data
      allData.ch1_data = socketData.ch1_data
      allData.ch2_data = socketData.ch2_data
      allData.ch3_data = socketData.ch3_data
      allData.collect_temperature = socketData.collect_temperature
      allData.time_type = socketData.time_type
      allData.time_value = socketData.time_value
      allData.systemInfo = socketData.systemInfo
      toGetCollectData(current_chid.value)
    }
  
    ws.value.onclose = (e) => {    
      console.log('[采集ws.onclose]: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
      if(e.wasClean) console.log('WebSocket连接已正常关闭');
      else ElMessage.error("websocket与采集CS软件未连接，采集CS软件可能已关闭，尝试重启CS并刷新网页")
    }
    
    ws.value.onerror = (e) => {
      console.log("[采集ws.onerror]:");
      // reConnect()
    }
  }
  let reConnect = () => {
    console.log("采集-尝试重新连接");
    if (isConnect) return; //如果已经连上就不在重连了
    rec && clearTimeout(rec);
    rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
      CreateWebSocket();
    }, 30000);
  };
  watch(storageFrames,async(newVal,oldVal) => {
    if(newVal !== 0 && newVal > oldVal && CurCollectPath.value >= 0){
      StorageRate.value = Number(((newVal - oldVal) / 5 * 2048 * 64 * CurCollectPath.value).toFixed(2))
    }
  })
  onMounted(async () => {
    CreateWebSocket() 
  })
  onUnmounted(async () => {
    // ws.value.close()//为了接收报警提示不断开
  })
  const stopOnePath = async (pathid:number) => {
    //TODO 调用接口发送要停止的采集通道号(0-3哪个通道，0-63哪个通路)
    CollectApi.postStop({"current_chid": current_chid.value, "pathid": pathid})
  }
  const stopAllPath = async () => {
    //调用接口发送指令停止所有通路
    CollectApi.stopAll()
  }
  const dialog = reactive({
      visible:false,
      type:"singlePath-form",
      width:400,
      title:""
  })
    const currentDDC_data = ref({
        "pathid":0,
        "freq":86.888,
        "gain":6,
        "amplitude": 200,
        "touch_time": "16:30:22" ,
        "frame_count": 1000
    })
    const openDialog = async (type:string,pathid:number) => {
        dialog.visible = true;
        dialog.type = type;
        
        if(pathid >= 0 && pathid <= 63){
            dialog.title = "修改采集参数";                    
            Object.assign(currentDDC_data.value,{...tableData.value[pathid]})
        }
    }

    const confirmModify = async () => {
    //TODO 发送接口给采集程序当前的采集通道参数
        currentDDC_data.value["current_chid"] = current_chid.value
        
        CollectApi.postModify(currentDDC_data.value)
        dialog.visible = false
    }

    const cancelModify =async () => {
        dialog.visible = false
    }
</script>

<style>
.systemInfo {
  display: flex;
  height:1.6rem;
  font-size: 0.8rem;
  text-align: center;
  align-items: center;
  margin: 0.2rem 0;
  padding: 0rem 0.2rem;
  background-color: #4C4D4F;
  color: aliceblue;
}
.resourceInfo {
  display: flex;
  height:1.6rem;
  font-size: 0.8rem;
  text-align: center;
  align-items: center;
  margin: 0.2rem 0;
  padding: 0 0.2rem;
  background-color: #4C4D4F;
  color: aliceblue;
}
.systemInfo,.resourceInfo > span {
  flex: 1;
  height: 1.6rem;
  text-align: center;
}

.systemInfo span:last-child { 
    text-align: right; 
}
.resourceInfo span:last-child { 
    text-align: right; 
}      
.systemInfo span:first-child { 
    text-align: left; 
}
.resourceInfo span:first-child { 
    text-align: left; 
}

.time {
  width: 36rem;
  height: 1.5rem;
  padding: 0 0.2rem;
  font-size: 0.8rem;
  align-items: center;
  float: right;
  background-color: #4C4D4F;
  color: aliceblue;
}
.time > span {
  text-align: center;
}
.time span:last-child { 
    text-align: right; 
}
.storageRate {
  margin: 0 4rem 0 0;
}

</style>